package com.das.mechanic_base.mvp.view.camera;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.loader.app.LoaderManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.das.mechanic_base.R;
import com.das.mechanic_base.R2;
import com.das.mechanic_base.adapter.camera.X3CameraPhotoAdapter;
import com.das.mechanic_base.adapter.camera.X3FolderAdapter;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseFragment;
import com.das.mechanic_base.bean.camera.CameraBean;
import com.das.mechanic_base.bean.camera.CameraCloseBean;
import com.das.mechanic_base.bean.camera.Folder;
import com.das.mechanic_base.bean.camera.ImageVideoBean;
import com.das.mechanic_base.mvp.contract.camera.CameraPhotoContract;
import com.das.mechanic_base.mvp.presenter.camera.X3CameraPhotoPresenter;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 施工-选择照片
 */
public class X3PhotoFragment extends X3BaseFragment<X3CameraPhotoPresenter> implements CameraPhotoContract.View , X3CameraPhotoAdapter.ItemCallback{

    @BindView(R2.id.tv_title)
    TextView tv_title;
    @BindView(R2.id.iv_icon)
    ImageView iv_icon;
    @BindView(R2.id.tv_next)
    TextView tv_next;
    @BindView(R2.id.rlv_photo)
    RecyclerView rlv_photo;
    @BindView(R2.id.iv_back)
    ImageView iv_back;
    @BindView(R2.id.iv_show)
    ImageView iv_show;

    private X3CameraPhotoAdapter photoAdapter;
    private X3FolderAdapter mFolderAdapter;

    /**
     * 可选的图片总数量
     */
    private int allNum = 0;

    private List<String> pathList = new ArrayList<>();

    /**
     * 所有图片和视频
     */
    private List<ImageVideoBean> allImageList = new ArrayList<>();

    private PopupWindow mFolderPop;
    private ValueAnimator showAnim;
    private ValueAnimator hideAnim;
    private View popView;
    private ViewGroup.LayoutParams popParams;

    @Override
    protected int getLayoutId() {
        return R.layout.x3_fragment_photo;
    }

    @Override
    protected void initView(View view) {
        initRecycler();
        if (mPresenter != null) {
            mPresenter.loadMediaList();
        }
        allNum = getActivity().getIntent().getIntExtra("allNum",9);
    }

    private void initRecycler() {
        rlv_photo.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        photoAdapter = new X3CameraPhotoAdapter(getActivity(), this,rlv_photo);
        rlv_photo.setAdapter(photoAdapter);

        mFolderAdapter = new X3FolderAdapter(getActivity());
    }

    @Override
    protected X3CameraPhotoPresenter createPresenter() {
        return new X3CameraPhotoPresenter();
    }

    @OnClick({R2.id.iv_back, R2.id.tv_next, R2.id.tv_title})
    public void onViewClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {// 退出
            if (getActivity() != null) {
                CameraCloseBean closeBean = new CameraCloseBean(2);
                EventBus.getDefault().post(closeBean);
                getActivity().finish();
                getActivity().overridePendingTransition(0, R.anim.activity_exit);
            }
        } else if (id == R.id.tv_title) {// 选择其他文件夹
            if (mFolderPop == null) {
                createPopupFolderList();
            }
            if (mFolderPop.isShowing()) {
                if (hideAnim != null) {
                    hideAnim.start();
                }
            } else {
                int[] position = new int[2];
                tv_title.getLocationOnScreen(position);
                mFolderPop.showAtLocation(tv_title, Gravity.NO_GRAVITY, position[0],
                        position[1] + tv_title.getHeight());
                iv_back.setVisibility(View.INVISIBLE);
                tv_next.setVisibility(View.INVISIBLE);
                iv_icon.setRotation(-270);
                if (showAnim != null) {
                    showAnim.start();
                }
            }
        } else if (id == R.id.tv_next) {// TODO 选中相册中的图片 点击下一步
            /**
             * 对从相册中选中的照片进行压缩
             */
            if (X3StringUtils.isListEmpty(pathList)) {
                return;
            }
            tv_next.setClickable(false);
            showLoading("");

            // 去除压缩 为了直接获取文件的最后修改时间
            setResultList(pathList);
        }
    }

    private void setResultList(List<String> newPathList) {

        CameraBean cameraBean = new CameraBean(X3Constent.CODE_GALLERY_REQUEST,newPathList);
        EventBus.getDefault().post(cameraBean);
        hideLoading();

        if (getActivity() != null) {
            getActivity().finish();
            getActivity().overridePendingTransition(0, R.anim.activity_top_exit);
        }
    }

    private void createPopupFolderList() {
        popView = View.inflate(getActivity(), R.layout.x3_photo_item, null);
        mFolderPop = new PopupWindow(popView, X3ScreenUtils.getScreenWidth(getActivity()), X3ScreenUtils.getScreenHeight(getActivity()) - X3ScreenUtils.dipToPx(70, getActivity()));
        //设置背景,这个没什么效果，不添加会报错
        mFolderPop.setBackgroundDrawable(null);
        //设置点击弹窗外隐藏自身
        mFolderPop.setFocusable(false);
        mFolderPop.setOutsideTouchable(false);
        mFolderPop.setOnDismissListener(() -> {
            iv_back.setVisibility(View.VISIBLE);
            tv_next.setVisibility(View.VISIBLE);
            iv_icon.setRotation(-90);
        });

        ListView lv_view = popView.findViewById(R.id.lv_view);
        lv_view.setAdapter(mFolderAdapter);
        lv_view.setOnItemClickListener((parent, view, position, id) -> {
            if (hideAnim != null) {
                hideAnim.start();
            }

            if (position == 0) {
                photoAdapter.setData(allImageList);
                tv_title.setText(getString(R.string.x3_near_photo));
            } else {
                Folder folder = (Folder) parent.getAdapter().getItem(position);
                if (null != folder) {
                    photoAdapter.setData(folder.images);
                    tv_title.setText(folder.name);
                }
            }
            // 滑动到最初始位置
            rlv_photo.smoothScrollToPosition(0);
        });

        popParams = lv_view.getLayoutParams();
        showAnim = ValueAnimator.ofInt(0, X3ScreenUtils.getScreenHeight(getActivity()) - X3ScreenUtils.dipToPx(70, getActivity()));
        showAnim.setDuration(300);
        showAnim.addUpdateListener(animation -> {
            popParams.height = (int) animation.getAnimatedValue();
            lv_view.setLayoutParams(popParams);
        });

        hideAnim = ValueAnimator.ofInt(X3ScreenUtils.getScreenHeight(getActivity()) - X3ScreenUtils.dipToPx(70, getActivity()), 0);
        hideAnim.setDuration(300);
        hideAnim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if (mFolderPop != null) {
                    mFolderPop.dismiss();
                }
            }
        });
        hideAnim.addUpdateListener(animation -> {
            popParams.height = (int) animation.getAnimatedValue();
            lv_view.setLayoutParams(popParams);
        });

    }

    @Override
    public void showMediaList(List<ImageVideoBean> imageList) {
        this.allImageList = imageList;
        if (X3StringUtils.isListEmpty(imageList)) {
            //ToastUtils.showMessage("未搜索到任何图片和视频！");
            return;
        }
        if (photoAdapter != null) {
            photoAdapter.setData(imageList);
        }
    }

    @Override
    public void showFolderList(List<Folder> folderList) {
        if (mFolderAdapter != null) {
            mFolderAdapter.setData(folderList);
        }
    }

    @Override
    public LoaderManager getSupportManager() {
        return getActivity().getSupportLoaderManager();
    }

    @Override
    public Activity getViewContext() {
        return getActivity();
    }

    @Override
    public int isAlbum() {
        return getActivity().getIntent().getIntExtra("isAlbum",0);
    }

    @Override
    public int isShowVideo() {
        return getActivity().getIntent().getIntExtra("showVideo",0);
    }

    @Override
    public void iOnCameraShow(int position) {
        ImageVideoBean image = photoAdapter.getItem(position);
        if (image == null) {
            return;
        }
        if (pathList.contains(image.path)) {
            pathList.remove(image.path);
            changeNextStatus(pathList.size() != 0);
        } else {
            // 判断选择数量问题
            if (allNum == pathList.size()) {
                X3ToastUtils.showMessage(String.format(getString(R.string.x3_picture_max_nine),allNum));
                return;
            }
            pathList.add(image.path);
            changeNextStatus(true);

        }
        photoAdapter.select(position);
    }

    @Override
    public void iOnCameraSelectShow(String path,boolean isFirst) {
        Glide.with(getContext()).load(path).into(iv_show);
    }

    private void changeNextStatus(boolean isNext) {
        tv_next.setEnabled(isNext);
    }

    @Override
    public void onDestroy() {
        hideLoading();
        if (showAnim != null) {
            showAnim.cancel();
        }
        if (mFolderPop != null) {
            mFolderPop.dismiss();
        }
        if (hideAnim != null) {
            hideAnim.cancel();
        }
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("相册页");
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("相册页");
    }
}
